package cerebrum.controller;

import cerebrum.common.ConfigPropertiesUtil;
import cerebrum.common.FileUtil;
import cerebrum.common.ThreadUtil;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;

import java.io.File;
import java.util.*;

/**
 * 利用jna设置壁纸
 */
public class WallpaperMotion extends Thread {
    public WallpaperMotion() {
        ThreadUtil.setTaskStatus(true);
    }

    public static String imagesPath = "";

    public static String getImagesPath() {
        return imagesPath;
    }

    public static void setImagesPath(String imagesPath) {
        WallpaperMotion.imagesPath = imagesPath;
    }

    public void run() {
        startRun(imagesPath);
    }

    public static void startRun(String filePath) {
        File file = new File(filePath);
        ArrayList<String> strings = new ArrayList<>();
        if (file.exists()) {
            File[] files = file.listFiles();
            Arrays.stream(files).forEach((File file1) -> {
                strings.add(file1.getPath());
            });
            //获取刷新频率
            Long frequency = Long.valueOf(ConfigPropertiesUtil.get("frequency"));
            dispatcher(strings, frequency);
        }
    }

    private static void dispatcher(ArrayList<String> files, Long frequency) {

        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {

            String img = "";

            @Override
            public void run() {
                Random random = new Random();
                int i = random.nextInt(files.size());
                img = files.get(i);
                change(img);
                if (ThreadUtil.getTaskStatus() == false) {
                    timer.cancel();// 停止定时器
                }

            }
        };
        timer.schedule(task, 0, frequency);// 立即执行一次，后面每隔3秒执行一次
    }

    private static void change(String img) {

        Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER,
                "Control Panel\\Desktop", "Wallpaper", img);
        //For windows XP, change to 0
        Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER,
                "Control Panel\\Desktop", "WallpaperStyle", "10"); //fill

        Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER,
                "Control Panel\\Desktop", "TileWallpaper", "0");   // no tiling

        // refresh the desktop using User32.SystemParametersInfo(), so avoiding an OS reboot

        int SPI_SETDESKWALLPAPER = 0x14;
        int SPIF_UPDATEINIFILE = 0x01;
        int SPIF_SENDWININICHANGE = 0x02;

        // User32.System
        boolean result = MyUser32.INSTANCE.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,
                img, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
    }

}
